package cn.sytton.taffe.framework.security.config;

import cn.sytton.taffe.framework.properties.auth.AuthProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 处理Api访问权限配置
 *
 * @author skyrock
 */
@Component
public class ApiConfig implements InitializingBean {

    /**
     * 内置匿名api, 只允许匿名访问,登录后不能访问
     */
    private String[] anonymousArray = {
            "/auth/login/**",
            "/auth/captcha/**",
            "/auth/sms/**",
            "/auth/sso/**",
        };

    /**
     * 内置不限制api, 不管登不登录都能访问, 一般用于静态资源
     */
    private String[] permitAllArray = {
            "/code/**",
//            "/doc/**",
            "/druid/**"
//            "/favicon.ico"
        };

    //application.yml 配置的api
    private final Set<String> permitAll;
    private final Set<String> anonymous;

    public ApiConfig(AuthProperties authProperties) {
        this.permitAll = authProperties.getApi().getPermitAll();
        this.anonymous = authProperties.getApi().getAnonymous();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        addAll();
    }

    private void addAll() {
        Set<String> anonymousSet = Arrays.stream(anonymousArray).collect(Collectors.toSet());
        anonymousSet.addAll(anonymous);
        anonymousArray = anonymousSet.toArray(new String[0]);

        Set<String> permitAllSet = Arrays.stream(permitAllArray).collect(Collectors.toSet());
        permitAllSet.addAll(permitAll);
        permitAllArray = permitAllSet.toArray(new String[0]);
    }

    public String[] getPermitAllArray() {
        return permitAllArray;
    }

    public String[] getAnonymousArray() {
        return anonymousArray;
    }

}
